package org.centsuse.intention_spring.invention.segmentation.clients;

import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.centsuse.intention_spring.invention.config.models.ModelConfig;
import org.centsuse.intention_spring.invention.config.models.ModelConfiguration;
import org.centsuse.intention_spring.invention.segmentation.dto.DpChatRequest;
import org.centsuse.intention_spring.invention.segmentation.dto.DpChatResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Service
@Slf4j
public class DeepSeekLegacyClient {

    /** 模型配置 */
    @Autowired
    private ModelConfiguration modelConfiguration;

//    @Value("${deepseek.api.api-key}")
    private String apiKey;

//    @Value("${deepseek.api.base-url}")
    private String baseUrl;

    private String model;

    private RestTemplate restTemplate;

    @Autowired
    private RestTemplateBuilder builder;

    @PostConstruct  // 确保依赖注入完成后执行
    public void init() {
        Map<String, ModelConfig> modelConfigs = modelConfiguration.getModelConfigMap();
        ModelConfig modelConfig = modelConfigs.get("deepseek-r1");
        log.info("Creating web client: {}", modelConfig);
        if (null != modelConfig) {
            this.baseUrl = modelConfig.getBaseUrl();
            this.apiKey = modelConfig.getApiKey();
            this.model = modelConfig.getModelName();
        }
        this.restTemplate = builder
                .rootUri(baseUrl)
                .defaultHeader("Authorization", "Bearer " + apiKey)
                .build();
    }

    public DeepSeekLegacyClient(ModelConfiguration modelConfiguration, RestTemplateBuilder builder) {
        this.restTemplate = builder
                .rootUri(baseUrl)
                .defaultHeader("Authorization", "Bearer " + apiKey)
                .build();
    }

    public DpChatResponse chatCompletion(DpChatRequest request) {
        String fullUrl = baseUrl + "/chat/completions";  // 手动拼接完整路径
        request.setModel(model);
        log.info("Sending request: {}", request);
        HttpEntity<DpChatRequest> entity = new HttpEntity<>(request);
        ResponseEntity<DpChatResponse> response = restTemplate.postForEntity(
                fullUrl,
                entity,
                DpChatResponse.class
        );
        log.info("Response : {}", response);
        return response.getBody();
    }
}


